<?php 
class Wechat
{
    private $_openid = '';
    private $_appid = '';
    private $_app_secret = '';
    private $_access_token='';
    private $_refresh_token='';
    private $_scope = '';
    private $_response_type='';
    private $_redirect_uri='';
    private $_state='';
    private $CI;
    
    public function __construct($config=NULL){
    	//CI实例
    	$this->CI = &get_instance();
        //默认能量逗服务号
    	$this->CI->config->load('weixin');
        $this->_appid = !isset($config['appid'])?$this->CI->config->item('nldou_fuwu_appid'):$config['appid'];
    	$this->_app_secret= !isset($config['appsecret'])?$this->CI->config->item('nldou_fuwu_appsecret'):$config['appsecret'];
    	$this->_response_type='code';
    	$this->_redirect_uri=!isset($config['redirect_uri'])? '' : $config['redirect_uri'];
    	$this->_refresh_token=!isset($config['refresh_token'])? '' : $config['refresh_token'];
    	$this->_scope=!isset($config['scope'])? '' : $config['scope'];
    }
    public function get_login_url()
    {
        $params['appid']         = $this->_appid;
        $params['redirect_uri']  = $this->_redirect_uri;
        $params['response_type'] = $this->_response_type;
        $params['scope']         = $this->_scope;
        $params['state']         = $this->_state;
               
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize";
        return $url . "?" . http_build_query($params) . "#wechat_redirect";
    }
    public function get_code()
    {
    	$url=$this->get_login_url();
    	if(empty($url)){
    		echo 'fail';
    		exit();
    	}else{
    		header("Location: {$url}");
    		exit();
    	}	
    }

    public function get_access_token()
    {
        $code = (empty($_REQUEST['code']) ? '' : $_REQUEST['code']);
        if(!empty($code)){
        	$token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->_appid.'&secret='.$this->_app_secret.'&code='.$code.'&grant_type=authorization_code';       	
        	$res = $this->https_request($token_url);
        	$info = json_decode($res, true);
        	$this->_openid = $info['openid'];
        	$this->_access_token=$info['access_token'];
        	$this->_refresh_token=$info['refresh_token'];
        } else{echo 'lack code';exit();}
    }
    
    public function cache_refresh_token()
    {
    	//缓存refresh_token,期限20天
    	$this->CI->load->driver('cache',array('adapter' => 'apc', 'backup' => 'file'));
    	$this->CI->cache->save('wechat_auth_refresh_token_'.$this->_openid, $this->_refresh_token, 3600*24*20);
    }
    
    public function refresh_access_token()
    {
    	$url="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=".$this->_appid."&grant_type=refresh_token&refresh_token=".$this->_refresh_token;
    	$res = $this->https_request($url);
    	$info = json_decode($res, true);
    	//没有错误设置access_token和openid
    	if(!isset($info['errcode'])){
    		$this->_access_token=$info['access_token'];
    		$this->_openid = $info['openid'];
    	}    	
    }
    
    public function check_access_token()
    {
    	$url="https://api.weixin.qq.com/sns/auth?access_token=".$this->_access_token."&openid=".$this->_openid;
    	$res = $this->https_request($url);
    	$info = json_decode($res, true);
    	if($info['errcode']==0){
    		return true;
    	}else{
    		return false;
    	}
    }
    
    public function get_openid()
    {
        return $this->_openid;
    }
    
    public function set_scope($scope){
    	$this->_scope=$scope;
    }
    
    public function set_redirect_uri($redirect_uri)
    {
    	$this->_redirect_uri=$redirect_uri;
    }
    public function set_state($state){
        $this->_state=$state;
    }

    public function get_user_info()
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?openid=" . $this->_openid .
            "&access_token=" . $this->_access_token;
        
        $res = $this->https_request($url);

        $user = json_decode($res, true);
        
        if (isset($user['errcode'])){
//         	echo "errcode：".$user['errcode'];
//         	echo "<br>";
//         	echo "errmsg：".$user['errmsg'];
            echo "获取信息失败，请重试";
        	return false;	
        }else{
        	$info['access_token']=$this->_access_token;
        	$info['openid']     = $user['openid'];
        	$info['province']   = empty($user['province'])?'':$user['province'];
        	$info['city']       = empty($user['city'])?'':$user['city'];
        	$info['country']    = empty($user['country'])?'':$user['country'];
        	//$info['privilege'];用户特权信息，json 数组，如微信沃卡用户为（chinaunicom）
        	$info['unionid']    = $user['unionid'];
        	switch ($user['sex']){
        		case '1':
        			$info['gender']='m';
        			break;
        		case '2':
        			$info['gender']='f';
        			break;
        		default:
        			$info['gender']='';
        	}
            $user['nickname'] = preg_replace_callback('/./u', function (array $match) {return strlen($match[0]) >= 4 ? '' : $match[0];}, $user['nickname']);
//            $user['nickname'] = preg_replace('/\xEE[\x80-\xBF][\x80-\xBF]|\xEF[\x81-\x83][\x80-\xBF]/', '', $user['nickname']);
        	$info['nickname'] = empty($user['nickname'])||!isset($user['nickname'])?'新问友':$user['nickname'];
        	$info['userIcon'] = empty($user['headimgurl'])||!isset($user['headimgurl'])?'/upload/images/default-user-icon.jpg':$user['headimgurl'];
        	return $info;
        }        
    }

    public function https_request($url,$data=null)
    {
    	$ch=curl_init();
    	curl_setopt($ch, CURLOPT_URL, $url);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    	if(!empty($data)){
    		curl_setopt($ch, CURLOPT_POST, 1);
    		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    
    	}
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    	$output=curl_exec($ch);
    	curl_close($ch);
    	return $output;
    }
}
